package com.jhd.fuzhou.view.knowledge;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.jhd.fuzhou.adapter.ShowAdapter;
import com.jhd.fuzhou.service.KnowledgeBaseService;
import com.jhd.fuzhou.util.GetImageByUrl;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.ArchiveService;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.view.archive.ArchiveDetailActivity;
import com.jhd.fuzhou.vo.ArchivesVo;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.KnowledgeFileVo;
import com.jhd.fuzhou.vo.KnowledgeShowVo;
import com.jhd.fuzhou.vo.SearchUnit;

import net.zigin.commons.util.StringUtil;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class KnowledgeBaseActivity extends BaseActivity {
    @BindView(R.id.recyclerView)RecyclerView recyclerView;
    private ProgressDialog _dialog;
    private Context context=this;
    private LinearLayoutManager layoutManager;
    @BindView(R.id.tv_loading)TextView tv_loading;
    @BindView(R.id.iv_cancel)ImageView iv_cancel;
    @BindView(R.id.et_search)EditText et_search;
    private SearchUnit searchUnit;
    private List<KnowledgeShowVo> knowledgeShowVoList=new ArrayList<>();
    private KnowledgeAdapter knowledgeAdapter;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_knowledge_base);
    }

    @Override
    protected void processLogic() {
        onBack();
        _dialog = new ProgressDialog(context);
        searchUnit=new SearchUnit();
        searchUnit.setPageIndex(1);
        searchUnit.setPageNum(1);//默认只有一页
        searchUnit.setKeyword(et_search.getText().toString());
        layoutManager = new LinearLayoutManager(context);
        recyclerView.setLayoutManager(layoutManager);
        getKnowledgePage();
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastCompletelyVisibleItemPosition = layoutManager.findLastCompletelyVisibleItemPosition();
                if(lastCompletelyVisibleItemPosition==layoutManager.getItemCount()-1){
                    tv_loading.setVisibility(View.VISIBLE);
                    searchUnit.setPageIndex(searchUnit.getPageIndex()+1);
                    if(searchUnit.getPageIndex()<=searchUnit.getPageNum()){
                        tv_loading.setText(getString(R.string.loading));
                        getKnowledgePage();
                    }else{
                        tv_loading.setText(getString(R.string.arrival_bottom));
                    }
                }else{
                    tv_loading.setVisibility(View.GONE);//没到底部，隐藏
                }
            }
        });
        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                searchUnit.setPageIndex(1);
                searchUnit.setKeyword(et_search.getText().toString());
                knowledgeShowVoList.clear();
                getKnowledgePage();
                return false;//当这里返回的为false时，表示还能再进行其他操作
            }
        });
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) { }
            @Override
            public void afterTextChanged(Editable s) {
                if(s.toString().equals("")){
                    searchUnit.setPageIndex(1);
                    searchUnit.setKeyword("");
                    knowledgeShowVoList.clear();
                    getKnowledgePage();
                    iv_cancel.setVisibility(View.GONE);
                }else{
                    iv_cancel.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @OnClick({R.id.iv_cancel})
    public void onClick(View v){
        switch (v.getId()){
            case R.id.iv_cancel:
                et_search.setText("");
                iv_cancel.setVisibility(View.GONE);
                break;
        }
    }

    private void getKnowledgePage() {
        if(!_dialog.isShowing()){
            _dialog.setMessage("正在获取文档管理列表,请稍等...");
            _dialog.show();
        }
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        KnowledgeBaseService vs = retrofit.create(KnowledgeBaseService.class);
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("pageIndex", searchUnit.getPageIndex());
        params.put("pageSize", 20);
        params.put("name", searchUnit.getKeyword());//模糊查询
        Call<JsonForResult> jsonForResultCall = vs.getKnowledgePage(application.getAccessToken(), params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                if(_dialog != null)_dialog.cancel();
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if (jsonForResult.getData() != null) {
                            List<KnowledgeShowVo> knowledgeShowVos = JSON.parseArray(jsonForResult.getData().toString(), KnowledgeShowVo.class);
                            for (KnowledgeShowVo knowledgeShowVo : knowledgeShowVos) {
                                knowledgeShowVoList.add(knowledgeShowVo);
                            }
                            if (searchUnit.getPageIndex() == 1) {
                                knowledgeAdapter = new KnowledgeAdapter();
                                recyclerView.setAdapter(knowledgeAdapter);
                            } else {
                                tv_loading.setVisibility(View.GONE);
                                knowledgeAdapter.notifyDataSetChanged();
                            }
                            searchUnit.setPageNum(jsonForResult.getTotal()/20+1);
                        } else {
                            knowledgeAdapter = new KnowledgeAdapter();
                            recyclerView.setAdapter(knowledgeAdapter);
                            tv_loading.setText(context.getString(R.string.arrival_bottom));
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    if(_dialog != null)_dialog.cancel();
//                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                if(_dialog != null)_dialog.cancel();
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg;
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    private class KnowledgeAdapter extends RecyclerView.Adapter<KnowledgeAdapter.ViewHolder> {
        @Override
        public KnowledgeAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_knowledge_base, parent, false);
            KnowledgeAdapter.ViewHolder viewHolder = new KnowledgeAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull KnowledgeAdapter.ViewHolder holder, int position) {
            List<KnowledgeFileVo> knowledgeFileVoList=knowledgeShowVoList.get(position).getKnowledgeCoverPictures();
            if(knowledgeFileVoList!=null&&knowledgeFileVoList.size()>0){
                if("1".equals(knowledgeFileVoList.get(0).getType())){
                    GetImageByUrl getImageByUrl = new GetImageByUrl();
                    getImageByUrl.setImage(holder.iv_knowledgeCoverPicture, knowledgeFileVoList.get(0).getUrl());
                }else{
                    holder.iv_knowledgeCoverPicture.setImageResource(R.mipmap.ic_no_pic);
                }
            }else{
                holder.iv_knowledgeCoverPicture.setImageResource(R.mipmap.ic_no_pic);
            }
            holder.tv_knowledge_base_name.setText(StringUtil.isNullOrEmpty(knowledgeShowVoList.get(position).getName())?"":knowledgeShowVoList.get(position).getName());
            holder.tv_knowledge_base_type.setText(StringUtil.isNullOrEmpty(knowledgeShowVoList.get(position).getTypeName())?"":knowledgeShowVoList.get(position).getTypeName());
            holder.tv_knowledge_base_dept.setText("颁布单位:"+(StringUtil.isNullOrEmpty(knowledgeShowVoList.get(position).getPublisher())?"":knowledgeShowVoList.get(position).getPublisher()));
            holder.tv_version_number.setText("版本号:"+(StringUtil.isNullOrEmpty(knowledgeShowVoList.get(position).getVersion())?"":knowledgeShowVoList.get(position).getVersion()));
            holder.linearLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(context, KnowledgeDetailActivity.class);
                    intent.putExtra("id",knowledgeShowVoList.get(position).getId());
                    startActivity(intent);
                }
            });
        }

        @Override
        public int getItemCount() {
            return knowledgeShowVoList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tv_knowledge_base_name, tv_knowledge_base_type, tv_knowledge_base_dept, tv_version_number;
            LinearLayout linearLayout;ImageView iv_knowledgeCoverPicture;

            public ViewHolder(View itemView) {
                super(itemView);
                this.tv_knowledge_base_name = itemView.findViewById(R.id.tv_knowledge_base_name);
                this.tv_knowledge_base_type = itemView.findViewById(R.id.tv_knowledge_base_type);
                this.tv_knowledge_base_dept = itemView.findViewById(R.id.tv_knowledge_base_dept);
                this.tv_version_number = itemView.findViewById(R.id.tv_version_number);
                this.iv_knowledgeCoverPicture = itemView.findViewById(R.id.iv_knowledgeCoverPicture);
                this.linearLayout = itemView.findViewById(R.id.linearLayout);
            }
        }
    }
}